#!/usr/bin/env node
var sys = require("sys"),
	fs = require("fs"),
	chat = require('./lib/server'),
	router = require("./lib/router"),
    msgCtrl = require('./lib/admin').msgCtrl,
    db = require('./config').db;
// create chat server
var chatServer = chat.createServer();
var saveLog = (function(){
    var pending = [];
    var logName = 'messageLog' + new Date().getFullYear() + '_' + new Date().getMonth() + '_'+ new Date().getDate() + '_' + new Date().getHours();
    var timer = setInterval(function(){
        if (pending.length == 0)
            return;
        fs.open(logName,'a+', function(err, fd){
            if (err){
                console.log(err);
            }else{
                var str = pending.join('\n') + '\n';
                fs.writeSync(fd,str + '\n');
                pending = [];
                fs.closeSync(fd);
            }
        });
    },10000);
    return function(msg){
        try{
            pending.push(JSON.stringify(msg));
        }catch(e){
            /*fs.open('./error.log','a+', function(err, fd){
                fs.writeSync(fd,e.message + '\n');
            });*/
        };
    };
})()
chatServer.listen(2011);
var online = 0, maxOnline = 0;
// create a channel and log all activity to stdout
var channel = chatServer.addChannel({
    basePath: "/chat"
});
msgCtrl.setChannel(channel);
channel.addListener("msg", function(msg) {
    saveLog(msg);
	//sys.puts("<" + msg.nick + "> " + msg.text);
}).addListener("join", function(msg) {
    online ++;
    //if (online > maxOnline)
    // /   maxOnline = online;
	//sys.puts(msg.nick + " join");
    fs.open("userStat",'a+', function(err, fd){
        if (err){
            console.log(err);
        }else{
            fs.writeSync(fd,'channel/chat:' + channel.online + '/' + channel.maxOnline + ' , Mem:' + process.memoryUsage().rss / 1024/1024 + '\n');
            fs.closeSync(fd);
        }
    });
}).addListener("part", function(msg) {
	//sys.puts(msg.nick + " part");
});
// server static web files
function serveFiles(localDir, webDir) {
	fs.readdirSync(localDir).forEach(function(file) {
		var local = localDir + "/" + file,
			web = webDir + "/" + file;
		if (fs.statSync(local).isDirectory()) {
			serveFiles(local, web);
		} else {
			chatServer.passThru(web, router.staticHandler(local));
		}
	});
}
serveFiles(__dirname + "/web", "");
//chatServer.passThru("/js/nodechat.js", router.staticHandler(__dirname + "/../web/nodechat.js"));
chatServer.passThru("/", router.staticHandler(__dirname + "/web/index.html"));
process.addListener("uncaughtException", function (err) {
    console.log("Uncaught exception: " + err);
    console.trace();
});
